import { clearUploadInfo } from '@/slices/uploadSlice';
import { ReactNode, useEffect, useRef } from 'react';
import { useDispatch } from 'react-redux';
import { useLocation, useNavigate } from 'react-router-dom';
import { setNavigate } from '@/config/axios/service';

interface RouteGuardProps {
  children: ReactNode;
}

const RouteGuard = ({ children }: RouteGuardProps) => {
  const navigate = useNavigate();
  const location = useLocation();
  const dispatch = useDispatch();
  const prevLocation = useRef(location.pathname);

  useEffect(() => {
    setNavigate(navigate);
  }, [navigate]);

  useEffect(() => {
    const handleRouteChange = () => {
      // 画面跳转，清空上传信息
      if (prevLocation.current === '/publish-model' || location.pathname === '/publish-model' ||
          prevLocation.current === '/train-model' || location.pathname === '/train-model') {
        dispatch(clearUploadInfo());
      }

      // 登录画面跳转
      if (location.pathname === '/login' 
            && !location.search.includes('redirect=')
            && prevLocation.current !== '/'
            && prevLocation.current !== '/login') {
        navigate('/login?redirect=' + prevLocation.current, { replace: true });
      }

      prevLocation.current = location.pathname;
    };

    handleRouteChange();

    return () => {};
  }, [navigate, location, dispatch]);

  return <>{children}</>;
};

export default RouteGuard;
